import axios from "axios"
import Vue from 'vue'
import router from '../router'
import store from '../store'

let alartTimeSpace = null;
Vue.prototype.errorInfo = function(msg){//如果连续弹出多个，只要弹出一个就好了
  if(!alartTimeSpace||alartTimeSpace+1000<new Date().getTime()){
    alartTimeSpace = new Date().getTime();
    this.$message({
      type: "warning",
      message: msg,
      onClose: function(){
        alartTimeSpace = null;
      }
    });
  }
}
Vue.prototype.reLogin = function(){
  router.push({path:"/login"});
}
axios.defaults.withCredentials = true;
axios.defaults.timeout = 60000;
axios.defaults.retry = 1;// 重试次数，加上本身共请求2次
axios.defaults.retryDelay = 1000;// 请求的间隙
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
  var config = err.config;
  if (!config || !config.retry)config.retry = axios.defaults.retry;
  if (!config.retry) return Promise.reject(err);// 如果配置不存在或未设置重试选项，则拒绝
  config.__retryCount = config.__retryCount || 0;// 设置变量以跟踪重试次数
  if (config.__retryCount >= config.retry) {// 判断是否超过总重试次数
    return Promise.reject(err);// 返回错误并退出自动重试
  }
  config.__retryCount += 1;// 增加重试次数
  console.log(config.url +' 自动重试第' + config.__retryCount + '次');//打印当前重试次数
  var backoff = new Promise(function (resolve) {// 创建新的Promise
    setTimeout(function () {
      resolve();
    }, config.retryDelay || axios.defaults.retryDelay || 1);
  });
  return backoff.then(function () {// 返回重试请求
    return axios(config);
  });
});
var qs = require('qs');//会将参数转为 get表单请求的方式，值是 key-value
//isform=true代表提交的是表单
const postData = (url, params, headers,isform=false) =>{
  return new Promise(function(resolve, rejectes){
    if(!headers){//application/json;//结构复杂的话使用json更合理
      headers = {
        "Content-Type": "application/json;"//默认值
      };
    }
    if(headers.hasOwnProperty("Content-Type")&&headers["Content-Type"].indexOf("application/x-www-form-urlencoded;")>-1&&!isform) {
      params = qs.stringify(params);
    }
    headers["Content-Type"] += " charset=UTF-8";
    if(url.indexOf('/v3/')==-1){
      url = "/v1"+url;
    }
    let option = {
      headers: headers,
      withCredentials: false,//不携带身份凭证，
      method: 'post',
      url: store.state.baseHost+url,
      data: params
    };
    axios(option).then(function(res){
      if(res.status==200&&(!res.data.code||res.data.code==200)){
        res.data.code = 0;
        resolve(res.data);
      }else {
        if(res.data.msg)Vue.prototype.errorInfo(res.data.msg);
        rejectes(res.data);
        if(res.data.code===401){
          router.replace({path:"/login"});
        }
      }
    }).catch(() => {
      rejectes({code:5000,msg: "我忙不过来了，请稍后再试~"});
    });
  });
}
const getData = (url, params) =>{
  return new Promise(function(resolve, rejectes){
    if(url.indexOf('/v3/')==-1){
      url = "/v1"+url;
    }
    let option = {
      withCredentials: false,//不携带身份凭证，
      method: 'get',
      url: store.state.baseHost+url,
      params: params
    };
    axios(option).then(function(res){
      if(!res.data.code||res.data.code==200){
        res.data.code = 0;
        resolve(res.data);
      }else {
        if(res.data.msg)Vue.prototype.errorInfo(res.data.msg);
        rejectes(res.data);
        if(res.data.code===401){
          router.replace({path:"/login"});
        }
      }
    }).catch(() => {
      rejectes({code:5000,msg: "我忙不过来了，请稍后再试~"});
    });
  });
}

export default {
  postData: postData,
  getData: getData,
}
